package org.nowcoder.leetcode.BTree;

import java.util.Stack;

/**
 * Title  : 110. Balanced Binary Tree
 * Source : https://leetcode.cn/problems/balanced-binary-tree/description/
 * Author : XrazYang
 * Date   : 2024-04-11
 */

public class LeetCode_110 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int getHeight(TreeNode root) {
        if (root == null) return 0;
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        Stack<TreeNode> sta = new Stack<>();
        sta.push(root);
        while (!sta.isEmpty()) {
            TreeNode node = sta.pop();
            int l = getHeight(node.left);
            int r = getHeight(node.right);
            if (Math.abs(r - l) > 1) return false;
            if (node.left != null) {
                sta.push(node.left);
            }
            if (node.right != null) {
                sta.push(node.right);
            }
        }
        return true;
    }
}
